package com.demo.myapplication.fragment;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RemoteViews;

import com.demo.myapplication.R;
import com.demo.myapplication.activity.MainActivity;

import java.util.Random;

public class NotificationFragment extends Fragment implements View.OnClickListener {

  private static String Tag = NotificationFragment.class.getSimpleName();
  private NotificationManager nm;

  private static final String NOTIFI_ID = "notifi_id";
  private int TEXT_NOTIFI_ID = 1;
  private int PROGRESS_NOTIFI_ID = 2;
  private int BIG_CONTENTVIEW_ID = 3;
  private int CUSTOM_VIEW = 4;
  private int CUSTOM_VIEW2 = 5;

  private static String PAUSE_NOTIFI = "com.demo.myapplication.pause_notifi";
  private static String REMOVE_NOTIFI = "com.demo.myapplication.remove_notifi";
  private static String START_NOTIFI = "com.demo.myapplication.start_notifi";

  public static Fragment newInstance(Bundle bundle) {
    NotificationFragment fragment = new NotificationFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  public NotificationManager getNM() {
    nm = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
    return nm;
  }

  private BroadcastReceiver notifiBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      if (intent.getAction().equals(PAUSE_NOTIFI)) {
        Log.d(Tag, "onReceive pause");
        //update notification
        showBigContentView(true);
      } else if (intent.getAction().equals(START_NOTIFI)) {
        Log.d(Tag, "onReceive start");
        showBigContentView();
      } else if (intent.getAction().equals(REMOVE_NOTIFI)) {
        Log.d(Tag, "onReceive remove");
        getNM().cancel(intent.getIntExtra(NOTIFI_ID, 0));
      }
    }
  };

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public void onStart() {
    super.onStart();
    IntentFilter filter = new IntentFilter();
    filter.addAction(PAUSE_NOTIFI);
    filter.addAction(START_NOTIFI);
    filter.addAction(REMOVE_NOTIFI);
    getActivity().registerReceiver(notifiBroadcastReceiver, filter);
  }

  @Override
  public void onStop() {
    super.onStop();
    getActivity().unregisterReceiver(notifiBroadcastReceiver);
  }

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_notification, container, false);
    view.findViewById(R.id.text_notification).setOnClickListener(this);
    view.findViewById(R.id.text_with_progress).setOnClickListener(this);
    view.findViewById(R.id.big_contentview).setOnClickListener(this);
    view.findViewById(R.id.custom_view).setOnClickListener(this);
    view.findViewById(R.id.custom_view2).setOnClickListener(this);
    return view;
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.text_notification:
        showTextNotification();
        break;
      case R.id.text_with_progress:
        showTextWithProgress();
        break;
      case R.id.big_contentview:
        showBigContentView();
        break;
      case R.id.custom_view:
        showCustomView();
        break;
      case R.id.custom_view2:
        showCustomView2();
        break;
      default:
        break;
    }
  }

  private NotificationCompat.Builder getBaseBuilder() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity());
    builder.setContentTitle(getActivity().getString(R.string.app_name))
        .setContentText(getActivity().getString(R.string.app_desc))
        .setContentInfo(getActivity().getString(R.string.progress))
        .setSmallIcon(R.drawable.ic_small_icon)
        .setAutoCancel(true);
    Intent intent = new Intent(getActivity(), MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);
    return builder;
  }

  private void showTextNotification() {
    NotificationCompat.Builder builder = getBaseBuilder();
    Notification textNotification = builder.build();
    getNM().notify(TEXT_NOTIFI_ID, textNotification);
  }

  private void showTextWithProgress() {
    NotificationCompat.Builder builder = getBaseBuilder();
    builder.setSmallIcon(android.R.drawable.stat_sys_download);
    builder.setProgress(0, 0, true);
    Notification n = builder.build();
    getNM().notify(PROGRESS_NOTIFI_ID, n);
  }

  private void showBigContentView() {
    showBigContentView(false);
  }

  private NotificationCompat.Builder bigContentViewBuilder;

  private void showBigContentView(boolean isStart) {
    bigContentViewBuilder = getBaseBuilder();
    if (isStart) {
      pause = true;
      Intent startIntent = new Intent();
      startIntent.setAction(START_NOTIFI);
      bigContentViewBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done);
      bigContentViewBuilder.addAction(R.drawable.ic_start, getActivity().getString(R.string.action_start), PendingIntent.getBroadcast(getActivity(), 0, startIntent, PendingIntent.FLAG_UPDATE_CURRENT));
    } else {
      pause = false;
      Intent pauseIntent = new Intent();
      pauseIntent.setAction(PAUSE_NOTIFI);
      bigContentViewBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
      bigContentViewBuilder.addAction(R.drawable.ic_pause, getActivity().getString(R.string.action_pause), PendingIntent.getBroadcast(getActivity(), 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT));
    }

    Intent removeIntent = new Intent();
    removeIntent.setAction(REMOVE_NOTIFI);
    removeIntent.putExtra(NOTIFI_ID, BIG_CONTENTVIEW_ID);

    if(progress >= 100) {
      progress = init_progress;
    }
    bigContentViewBuilder.setProgress(100, progress, false)
        .setContentInfo(progress + "M/100M")
        .addAction(R.drawable.ic_remove, getActivity().getString(R.string.action_remove), PendingIntent.getBroadcast(getActivity(), 0, removeIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    Notification n = bigContentViewBuilder.build();
    getNM().notify(BIG_CONTENTVIEW_ID, n);
    new Thread(new Runnable() {
      @Override
      public void run() {
        while (progress <= 100 && !pause) {
          int random = new Random().nextInt(10) + 1;
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          progress += random;
          updateProgress(bigContentViewBuilder, progress);
        }
      }
    }).start();
  }

  private boolean pause = false;
  private int init_progress = 1;
  private int progress = init_progress;

  private void updateProgress(NotificationCompat.Builder builder, int progress) {
    if (progress >= 100) {
      init_progress = 1;
      builder.setProgress(0, 0, false)
          .setContentInfo("100M/100M")
          .setSmallIcon(android.R.drawable.stat_sys_download_done)
          .setContentText(getString(R.string.down_finish));
    } else {
      builder.setProgress(100, progress, false)
          .setSmallIcon(android.R.drawable.stat_sys_download)
          .setContentInfo(progress + "M/100M")
          .setContentText(getString(R.string.downing));
    }
    Notification n = builder.build();
    getNM().notify(BIG_CONTENTVIEW_ID, n);
  }

  private void showCustomView() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity());

    Intent intent = new Intent(getActivity(), MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    RemoteViews remoteViews = new RemoteViews(getActivity().getPackageName(), R.layout.notification_custom);
//    remoteViews.setImageViewResource(R.id.ic_image, R.drawable.ic_book);
    remoteViews.setTextViewText(R.id.down_name, getActivity().getString(R.string.app_name));
//    remoteViews.setTextViewText(R.id.down_status, getActivity().getString(R.string.down_status_demo));
//    remoteViews.setTextViewText(R.id.down_progress_text, getActivity().getString(R.string.down_progress_text_demo));
//    remoteViews.setProgressBar(R.id.down_progress, 100, 20, false);

    Intent removeIntent = new Intent();
    removeIntent.setAction(REMOVE_NOTIFI);
    removeIntent.putExtra(NOTIFI_ID, CUSTOM_VIEW);

    builder
        .setSmallIcon(R.drawable.ic_small_icon)
        .setContentText(getActivity().getString(R.string.down_status_demo))
        .setContentTitle(getActivity().getString(R.string.down_name_demo))
//        .setOngoing(true)
        .setAutoCancel(true)
        .setContent(remoteViews)
        .setContentIntent(contentIntent)
//        .addAction(R.drawable.ic_remove, getActivity().getString(R.string.action_remove), PendingIntent.getBroadcast(getActivity(), 0, removeIntent, PendingIntent.FLAG_UPDATE_CURRENT))
        .setWhen(System.currentTimeMillis());

    Notification n = builder.build();
    // set big content view for newer androids
    if (android.os.Build.VERSION.SDK_INT >= 16) {
      n.bigContentView = remoteViews;
      remoteViews.setTextColor(R.id.down_name, ContextCompat.getColor(getActivity(), android.R.color.black));
      remoteViews.setTextColor(R.id.down_status, ContextCompat.getColor(getActivity(), android.R.color.black));
      remoteViews.setTextColor(R.id.down_progress_text, ContextCompat.getColor(getActivity(), android.R.color.black));
    }
//    n.contentView = remoteViews;

    getNM().notify(CUSTOM_VIEW, n);
  }

  private void showCustomView2() {
    final RemoteViews rv = new RemoteViews(getActivity().getPackageName(), R.layout.fragment_notification2);

    rv.setImageViewResource(R.id.remoteview_notification_icon, R.mipmap.ic_launcher);

    rv.setTextViewText(R.id.remoteview_notification_headline, "Headline");
    rv.setTextViewText(R.id.remoteview_notification_short_message, "Short Message");
    rv.setTextColor(R.id.remoteview_notification_headline, ContextCompat.getColor(getActivity(), R.color.colorAccent));
    rv.setTextColor(R.id.remoteview_notification_short_message, ContextCompat.getColor(getActivity(), R.color.colorAccent));
// build notification
    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(getActivity())
            .setSmallIcon(R.drawable.ic_small_icon)
            .setContentTitle("Content Title")
            .setContentText("Content Text")
            .setContent(rv)
            .setPriority(NotificationCompat.PRIORITY_MIN);

    final Notification notification = mBuilder.build();

// set big content view for newer androids
    if (android.os.Build.VERSION.SDK_INT >= 16) {
      notification.bigContentView = rv;
    }

    getNM().notify(CUSTOM_VIEW2, notification);
  }
}
